package com.hyacinth.lotterysystem.dao.handler;


import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Slf4j
@MappedTypes(Encrypt.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class EncryptTypeHandler extends BaseTypeHandler<Encrypt> {
    // 密钥
    private byte[] KEY = "9e2ee370fcd14905889c1030c05fd195".getBytes(StandardCharsets.UTF_8);

    /**
     * 处理参数
     *
     * @param ps        SQL 预编译对象
     * @param i         索引位置
     * @param parameter 原本位置的i需要的赋值
     * @param jdbcType  类型
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Encrypt parameter, JdbcType jdbcType) throws SQLException {
        if (parameter == null || parameter.getValue() == null) {
            ps.setString(i, null);
            return;
        }
        AES aes = SecureUtil.aes(KEY);
        log.info("手机号原数据: {}", parameter.getValue());
        String str = aes.encryptHex(parameter.getValue());
        log.info("获取到的加密内容: {}", str);
        ps.setString(i, str);
    }

    /**
     * 获取值
     *
     * @param rs         结果集
     * @param columnName 索引名
     * @return
     * @throws SQLException
     */
    @Override
    public Encrypt getNullableResult(ResultSet rs, String columnName) throws SQLException {
        log.info("获取到的加密内容: {}", rs.getString(columnName));
        return decrypt(rs.getString(columnName));
    }

    /**
     * 获取值
     *
     * @param rs
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public Encrypt getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        log.info("获取到的加密内容: {}", rs.getString(columnIndex));
        return decrypt(rs.getString(columnIndex));
    }

    /**
     * 获取值
     *
     * @param cs
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public Encrypt getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        log.info("获取到的加密内容: {}", cs.getString(columnIndex));
        return decrypt(cs.getString(columnIndex));
    }

    /**
     * 解密
     *
     * @param str
     * @return
     */
    private Encrypt decrypt(String str) {
        if (!StringUtils.hasText(str)) {
            return null;
        }

        return new Encrypt(SecureUtil.aes(KEY).decryptStr(str));
    }
}
